

let baseUrl = "http:/192.168.10.204:7018";
let env = "pro";
if (env === "test") {
    baseUrl = "http://192.168.10.211:9080/ai";
} else {
    baseUrl = "http://gateway.lsmedia.com/ai";
}

$(function () {
    $('#loginBtn').click(function () {
        const targetUrl = 'http://userweb.lsmedia.com/#/login?redirect=/dashboard';
        chrome.tabs.create({ url: targetUrl });
    });

    chrome?.runtime?.onMessage.addListener(function (message, sender, sendResponse) {
        if (message.action === 'userLogin') {
            let userInfo = localStorage.getItem("userInfo")
            if (userInfo !== null) {
                console.log("已经登录过了")
                chrome.sidePanel.setOptions({ path: "sidebar/sidebar.html", });
                return
            }

            console.log(message.token)
            let msgBody = { token: message.token }

            console.log("切换侧边栏")
            requestUserLogin(msgBody).then(function (result) {
                if (result.code === 0) {
                    userInfo = result.data
                    localStorage.setItem("userInfo", JSON.stringify(result.data))
                    chrome.sidePanel.setOptions({ path: "sidebar/sidebar.html", });
                }
            })
        } else if (message.action === 'userLogout') {
            localStorage.removeItem("userInfo")
            chrome.sidePanel.setOptions({ path: "sidebar/login.html", });
        }
        return true;
    });
});

async function requestUserLogin(msgBody) {
    try {
        const response = await fetch(baseUrl + "/user/login", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(msgBody),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('请求出错:', error);
    }
}